package com.gitee.cui.http.netty.echo;

import com.gitee.cui.config.SystemConfig;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import lombok.extern.slf4j.Slf4j;

/**
 * Http请求回显服务端
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/10/28 16:09
 **/
@Slf4j
public class HttpEchoServer {

    /**
     * 启动Http请求回显服务端
     */
    public static void runServer () {
        EventLoopGroup boss = new NioEventLoopGroup(1);
        EventLoopGroup worker = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(boss, worker)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new HttpZeroCopyInitializer());

            ChannelFuture future = bootstrap.bind(SystemConfig.SOCKET_SERVER_PORT).sync();
            log.info("HTTP ECHO 服务已启动，http://{}:{}/", SystemConfig.SOCKET_SERVER_IP, SystemConfig.SOCKET_SERVER_PORT);
            ChannelFuture closeFuture = future.channel().closeFuture();
            closeFuture.sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            worker.shutdownGracefully();
            boss.shutdownGracefully();
        }
    }

    static class HttpZeroCopyInitializer extends ChannelInitializer<SocketChannel> {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast(new HttpRequestDecoder());
            pipeline.addLast(new HttpResponseEncoder());
            pipeline.addLast(new HttpObjectAggregator(65535));
            pipeline.addLast(new HttpEchoHandler());
        }
    }
}
